<template>
  <div class="my-cover">
    <!-- 图片按钮 -->
    <div class="btn_img" @click="showDialog">
      <!-- <img src="@/assets/default.png" alt=""> -->
      <!-- 避免把本地的图片放到data中，因为这样不会被webpack打包 -->
      <img :src="showImage" style="object-fit:cover"/>
    </div>
    <el-dialog
      title="选择封面"
      :visible.sync="dialogVisible"
      width="960">
      <!-- tab栏 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="picture">
          <el-radio-group v-model="collect" @change="change">
            <el-radio-button :label="false">全部</el-radio-button>
            <el-radio-button :label="true">收藏</el-radio-button>
          </el-radio-group>
          <!-- 布局 -->
          <el-row :gutter="10">
            <el-col @click.native="select(item.url)" :span="6" v-for="item in pictures" :key="item.id">
              <el-image :class="{active: item.url === selectImageUrl}" style="width: 100%; height: 180px;" :src="item.url" fit="cover"></el-image>
            </el-col>
          </el-row>
          <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-size="per_page"
            layout="total, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="upload">
          <!-- http-request : 自己实现上传功能 -->
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="upload"
          >
            <img v-if="uploadImageUrl" :src="uploadImageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getPictureList, uploadPicture } from '@/api/picture'
// import img from '@/assets/default.png'
// const img1 = require('@/assets/default.png')
export default {
  props: ['value'],
  data () {
    return {
      dialogVisible: false,
      activeName: 'picture',
      // 是否收藏
      collect: false,
      // 存放图片数据
      pictures: [],
      page: 1,
      per_page: 8,
      total: 0,
      // 保存选中的图片的地址
      selectImageUrl: '',
      uploadImageUrl: '',
      // 最终展示的图片
      showImage: this.value || require('@/assets/default.png')
    }
  },
  watch: {
    // 监听value的变化，如果value变化了，子组件的showImage需要重新赋值
    value () {
      this.showImage = this.value || require('@/assets/default.png')
    }
  },
  methods: {
    async getList () {
      const res = await getPictureList({
        page: this.page,
        per_page: this.per_page,
        collect: this.collect
      })
      const { results, total_count } = res.data
      console.log(res)
      this.total = total_count
      this.pictures = results
    },
    async showDialog () {
      this.dialogVisible = true
      this.getList()
    },
    handleCurrentChange (value) {
      this.page = value
      this.getList()
    },
    change () {
      this.page = 1
      this.getList()
    },
    select (url) {
      console.log(url)
      this.selectImageUrl = url
    },
    async upload ({ file }) {
      if (file.size >= 1024 * 1024) {
        this.$message.error('上传图片不能超过40KB')
        return false
      }
      const allowList = ['image/gif', 'image/png']
      if (!allowList.includes(file.type)) {
        this.$message.error('图片格式错误')
        return false
      }
      const fd = new FormData()
      fd.append('image', file)
      const res = await uploadPicture(fd)
      this.uploadImageUrl = res.data.url
    },
    /*
      1. 根据activeName判断当前的tab的名字
      2. 如果是upload,判断uploadImageUrl不能为空
        如果为空，给提示，如果不为空，把uploadImageUrl赋值给showImage
      3. 如果是picture,判断selectImageUrl 不能为空
        如果为空，给提示 如果不为空，把selectImageUrl赋值给showImage
    */
    confirm () {
      if (this.activeName === 'picture') {
        // 素材
        if (this.selectImageUrl) {
          this.showImage = this.selectImageUrl
          this.dialogVisible = false
        } else {
          return this.$message.warning('请选择一张图片')
        }
      } else {
        // 上传
        if (this.uploadImageUrl) {
          this.showImage = this.uploadImageUrl
          this.dialogVisible = false
        } else {
          return this.$message.warning('请上传一张图片')
        }
      }
      // 确定好了图片  showImage
      this.$emit('input', this.showImage)
    }
  }
}
</script>

<style scoped lang='less'>
// 图片按钮
.btn_img {
  width: 150px;
  height: 150px;
  border: 1px dashed #ddd;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
}
.el-row {
  margin-top: 20px;
  .el-col {
    margin-top: 8px;
  }
}
.active {
  position: relative;
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    // background-color: rgba(0, 0, 0, .5);
    // background-image: url('~@/assets/selected.png');
    // background-size: 80px 80px;
    // background-repeat: no-repeat;
    // background-position: center;
    background: rgba(0, 0, 0, .5) url('~@/assets/selected.png')  no-repeat center / 80px 80px;
  }
}
</style>
